﻿using System;
using System.Collections.Generic;

namespace Core
{
    public class UIWidgetSlice : UIWidget
    {
        protected readonly List<UIWidget> list = new();

        public UIWidget Curr { get; private set; }
        public int Index { get; private set; }
        public bool Loop { get; set; } = false;

        public void Add(UIWidget w)
        {
            if (list.Contains(w) == false)
            {
                list.Add(w);
            }
        }

        public void Remove(UIWidget w)
        {
            if (list.Contains(w))
            {
                list.Remove(w);
            }
        }

        public void SetIndex(int i)
        {
            if (i < 0 || i >= list.Count)
            {
                return;
            }

            Curr?.SetActive(false);
            Curr = list[i];
            Index = i;
            Curr.SetActive(true);
        }

        public void Next()
        {
            if (Loop == false)
            {
                if (Index >= list.Count) return;

                SetIndex(Index + 1);
            }
            else
            {
                var idx = Utils.Math.GetMod(Index + 1, list.Count);

                SetIndex(idx);
            }
        }

        public void Prev()
        {
            if (Loop == false)
            {
                if (Index <= 0) return;

                SetIndex(Index - 1);
            }
            else
            {
                var idx = Utils.Math.GetMod(Index - 1, list.Count);
                SetIndex(idx);
            }
        }

        public void Foreach<T>(Action<T> func)
        {
            if (func == null) return;

            for (var i = 0; i < list.Count; i++)
            {
                var item = list[i];
                if (item is T t)
                {
                    func.Invoke(t);
                }
            }
        }
    }
}
